﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class UIManager
{
    GameObject UIRoot;
    Dictionary<string, BaseWidget> AllWidgets = new Dictionary<string,BaseWidget>();
    List<UILayer> UILayers  ;

    EC_Table UIWidgetTable;
    EC_Table UILayerTable;

    public void Init(EC_Table widgetTable, EC_Table layerTable)
    {
        UIWidgetTable = widgetTable;
        UILayerTable = layerTable;
        this.UILayers = new List<UILayer>();
        UIRoot = (GameObject)GameObject.Instantiate(Resources.Load("Prefab/UI/UIRoot"));
        UIRoot.name = "UIRoot";
        int i = 0;
        foreach (KeyValuePair<string, List<EC_Row>> item in UILayerTable.TableRows)
        {
            UILayer layer = new UILayer(item.Value[0], i, UIRoot.transform);
            this.UILayers.Add(layer);
            i++;
        }
    }

    public BaseWidget Show(string widgetName) 
    {
      EC_Row row = UIWidgetTable.GetRow(widgetName,0);
      int layer = row.Value<int>("Layer");
      GameObject widgetGO = this.UILayers[layer].ShowWidget(widgetName,row);
      if (widgetGO!=null) 
      {
          widgetGO.name = widgetName;
          BaseWidget Widget = widgetGO.GetComponent<BaseWidget>();
          Widget.IsRootWidget = row.Value<bool>("IsRootWidget");
          AllWidgets.Add(widgetName, Widget);
          Widget.OnLoad();
          return Widget; 
      }
      return null;
    }
    public void Close(string widgetName) 
    {
        EC_Row row = UIWidgetTable.GetRow(widgetName, 0);
        int layer = row.Value<int>("Layer");
        if (AllWidgets.ContainsKey(widgetName))
        {
            this.UILayers[layer].CloseWidget(widgetName);
            this.AllWidgets[widgetName].OnExit();
            this.AllWidgets.Remove(widgetName);

        }
    }

    public GameObject GetPrefab(string name) 
    {
        EC_Row row = UIWidgetTable.GetRow(name, 0);
        return (GameObject)Resources.Load(row.Value<string>("PrefabPath"));
    }

    public T Get<T>(string widgetName) where T :BaseWidget 
    {
        if (this.AllWidgets.ContainsKey(widgetName)) 
        {
            return (T)this.AllWidgets[widgetName];
        }
        return null;
    }

    public GameObject LoadWidget(string widgetName) 
    {
        return null;
    }




    #region Tool Function
     public GameObject AddChild(GameObject parent, GameObject prefab)
    {
        GameObject go = GameObject.Instantiate(prefab) as GameObject;
        if (go != null && parent != null)
        {
            Transform t = go.transform;
            t.parent = parent.transform;
            t.localPosition = Vector3.zero;
            t.localRotation = Quaternion.identity;
            t.localScale = Vector3.one;
            go.layer = parent.layer;
        }
        return go;
    }
    #endregion
}
